var gcs_waypoints_list = [];  // waypoint on gcs is different with uav_waypoint_list
var waypoint_markers_list = [];
var waypoint_polyline = null;
var waypoint_polyline_points_list = [];

var SPOT_SIZE = 40;
var point_icon = new BMap.Icon("images/waypoint.png", new BMap.Size(SPOT_SIZE, SPOT_SIZE));
var point_icon_dark = new BMap.Icon("images/waypoint-dark.png", new BMap.Size(SPOT_SIZE, SPOT_SIZE));
var point_icon_orange = new BMap.Icon("images/waypoint-orange.png", new BMap.Size(SPOT_SIZE, SPOT_SIZE));
point_icon.setImageSize(new BMap.Size(SPOT_SIZE, SPOT_SIZE));
point_icon_dark.setImageSize(new BMap.Size(SPOT_SIZE, SPOT_SIZE));
point_icon_orange.setImageSize(new BMap.Size(SPOT_SIZE, SPOT_SIZE));
var wp_mark_offset = new BMap.Size(0,-20);
var PLANE_SIZE = new BMap.Size(35, 50);
var plane_icon = new BMap.Icon("images/plane.png", PLANE_SIZE);
plane_icon.setImageSize(PLANE_SIZE);
var cur_gps_lat = 0;
var cur_gps_lng = 0;
var last_pos = 0;
var overall_dis = 0;
var dis_from_home = 0;
var plane_marker = null;

function WayPoint(lat, lng, num, yaw, altitude, spd, hld_time, do_action){
  this.lat = lat;
  this.lng = lng;
  this.index = num;
  this.yaw = yaw;
  this.alt = altitude;
  this.speed = spd;
  this.hold_time = hld_time;
  this.action = do_action;
}

var WP_ACTION_NOTHING = 0;
var WP_ACTION_LAND = 1;
var WP_ACTION_RTL = 2;
var WP_HOME_DEFAULT_LNG = 116.352634;
var WP_HOME_DEFAULT_LAT = 39.985821;
var WP_DEFAULT_YAW = 0;
var home_valid = false;
var home_lng = WP_HOME_DEFAULT_LNG;
var home_lat = WP_HOME_DEFAULT_LAT;
var home_wp = new WayPoint(WP_HOME_DEFAULT_LAT, WP_HOME_DEFAULT_LNG, 0, 0, 0, 0, 0, WP_ACTION_NOTHING);

var merge = function() {
  return Array.prototype.concat.apply([], arguments)
}

function update_home(valid, lng, lat){
  if(home_wp == undefined || home_wp == null) return;
  if(valid){
    home_valid = true;
    home_wp.lat = lat;
    home_wp.lng = lng;
    if(waypoint_markers_list.length > 0){
      var bd09 = wgs84tobd09(lng, lat);
      waypoint_markers_list[0].setPosition(new BMap.Point(bd09[0], bd09[1]));
    }
  }
  else{
    home_valid = false;
    home_wp.lat = WP_HOME_DEFAULT_LAT;
    home_wp.lng = WP_HOME_DEFAULT_LNG;
    if(waypoint_markers_list.length > 0){
      var bd09 = wgs84tobd09(WP_HOME_DEFAULT_LNG, WP_HOME_DEFAULT_LAT);
      waypoint_markers_list[0].setPosition(new BMap.Point(bd09[0], bd09[1]));
    }
  }
  redraw_waypoint_polyline();
}

// playback
function onPlaybackListClick(){
  request_pbinfo(cur_pb_name);
  /*request_pbinfo('VCTFA165002-2016-07-13-17-39-02');*/
}

function request_pbtrack(pbname){
  var xmlhttp;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      //document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
      /*console.log(xmlhttp.responseText);*/
      track_points_data = xmlhttp.responseText;
      var line = track_points_data.split('\n')[1];
      var item = line.split(',');
      var lng = parseFloat(item[1])/1E7
      var lat = parseFloat(item[2])/1E7
      update_home(true, lng, lat);
      var bd09 = wgs84tobd09(lng, lat);
      map_center = new BMap.Point(bd09[0], bd09[1]);
      /*init_playback(xmlhttp.responseText);*/
    }
  }
  //xmlhttp.open("GET","/flight_history?uavid=VCTFA16B001",true);
  xmlhttp.open("GET","/pbtrack?pbname="+pbname,true);
  xmlhttp.send();
}

function request_pbwp(pbname){
  var xmlhttp;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      //document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
      console.log(xmlhttp.responseText);
      /*init_playback(xmlhttp.responseText);*/
    }
  }
  //xmlhttp.open("GET","/flight_history?uavid=VCTFA16B001",true);
  xmlhttp.open("GET","/pbwp?pbname="+pbname,true);
  xmlhttp.send();
}

function request_pbinfo(pbname){
  var xmlhttp;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      /*console.log(xmlhttp.responseText);*/
      init_playback(xmlhttp.responseText);
    }
  }
  //xmlhttp.open("GET","/flight_history?uavid=VCTFA16B001",true);
  xmlhttp.open("GET","/pbinfo?pbname="+pbname,true);
  xmlhttp.send();
}

function request_pbseg(pbname, start_index, end_index){
  var xmlhttp;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      //document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
      /*console.log(xmlhttp.responseText);*/
      var pb_seg = JSON.parse(xmlhttp.responseText);
      console.log(pb_seg.start_index);
      console.log(pb_seg.end_index);
      var start = pb_seg.start_index;
      var end = pb_seg.end_index;
      if(start != win_right){
        win_left = start;
        win_right = end;
        pb_lines = null;
        pb_lines = [];
        pb_lines = pb_seg.pb_segment;
        console.log('win_right changed to '+ win_right);
        console.log('win_left changed to '+ win_left);
        console.log('pb_lines length '+ pb_lines.length);
        pb_move_to(index_move_to);
      }
      else{
        /*console.log('pb_lines length '+ pb_lines.length);*/
        var new_lines = pb_seg.pb_segment;
        /*console.log(typeof(new_lines))*/
        /*console.log(new_lines.length)*/
        /*pb_lines.concat(new_lines);*/
        pb_lines = merge(pb_lines, new_lines);
        win_right = end;
        console.log('win_right changed to '+ win_right);
        console.log('pb_lines length '+ pb_lines.length);
        on_next_loading = false;
      }
      /*init_playback(xmlhttp.responseText);*/
    }
  }
  //xmlhttp.open("GET","/flight_history?uavid=VCTFA16B001",true);
  xmlhttp.open("GET","/pbseg?pbname="+pbname+'&start='+start_index+'&end='+end_index, true);
  /*xmlhttp.open("GET","/pbseg?pbname="+pbname, true);*/
  xmlhttp.send();
}

function request_flight_history(uavid){
  var xmlhttp;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      //document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
      /*console.log(xmlhttp.responseText);*/
      var data = xmlhttp.responseText;
      var rd_lines = data.split('\n');
      /*console.log(rd_lines.length);*/
      // init page numbers
      recordNum = rd_lines.length-1;
      console.log(recordNum);
      for(var i=rd_lines.length-2;i>=0;i--){
        var flight = JSON.parse(rd_lines[i]);
        flight_his_list.push(flight);
      }
      initFlyPages();
    }
  }
  //xmlhttp.open("GET","/flight_history?uavid=VCTFA16B001",true);
  xmlhttp.open("GET","/flight?uavid="+uavid,true);
  xmlhttp.send();
}

var PB_MSG_TYPE_HEARTBEAT = 0;
var PB_MSG_TYPE_ATTITUDE = 1;
var PB_MSG_TYPE_GPS_RAW_INT = 2;
var PB_MSG_TYPE_SYS_STATUS = 3;
var PB_MSG_TYPE_RC_CHANNELS = 4;
var PB_MSG_TYPE_MISSION_CURRENT = 5;
var PB_MSG_TYPE_GLOBAL_POSITION = 6;

var pb_base_status = {
  time: 0,
  system_is_armed : false,
  armed: 0,
  custom_mode : 0,
  base_mode : 0,
  frame_type : 0,
  autopilot_type : 0,
  system_status :0
}

var pb_sys_status = {
  time: 0,
  cpu_load : 0,
  sensors_present : 0,
  sensors_enabled : 0,
  sensors_health : 0,
  battery_voltage : 0,
  battery_current : 0,
  battery_remaining : 0
}

var pb_attitude = {
  time: 0,
  time_boot_ms : 0,
  roll : 0,
  pitch : 0,
  yaw : 0,
  rollspeed : 0,
  pitchspeed : 0,
  yawspeed : 0
}

var pb_global_position = {
  time: 0,
  lat : 0,
  lon : 0,
  alt : 0,
  relative_alt : 0,
  vx : 0,
  vy : 0,
  vz : 0,
  hdg : 0
}

var pb_gps_raw_int = {
  time: 0,
  time_usec: 0,
  lat: 0,
  lon: 0,
  alt: 0,
  eph: 9999,
  epv: 65535,
  vel: 0,
  cog: 0,
  fix_type: 0,
  satellites_visible: 0
}

var pb_rc_channels = {
  chan1_raw:0,
  chan2_raw:0,
  chan3_raw:0,
  chan4_raw:0,
  chan5_raw:0,
  chan6_raw:0,
  chan7_raw:0,
  chan8_raw:0
}

var pb_mission_current =  {
  seq: 0
}

var pb_cur_index = 1;
var pb_paused = false;
var total_time = 0;
var start_index = 12;
var end_index = 0;
var gcs_waypoints_list = [];
/*var cur_pb_name = 'VCTFA165002-2016-07-13-17-39-02';*/
/*var cur_pb_name = 'VCTFB166003-2016-07-16-15-47-28';*/
var track_points_data = "";

function init_playback(data){
  // clear map
  clear_track_line();
  clear_wp_on_map();
  request_pbtrack(cur_pb_name);
  // init gcs waypoints
  /*console.log(data);*/
  var pbinfo = JSON.parse(data);
  gcs_waypoints_list = JSON.parse(pbinfo.waypoints);
  for(var i=0;i<gcs_waypoints_list.length;i++){
    var cur_wp = gcs_waypoints_list[i];
    var bd09 = wgs84tobd09(cur_wp.lng, cur_wp.lat);
    draw_new_wp(new BMap.Point(bd09[0], bd09[1]), i);
    if(i>0) marker_points.push(new BMap.Point(bd09[0], bd09[1]));
  }
  redraw_waypoint_polyline();
  if(gcs_waypoints_list.length > 0){
    if(gcs_waypoints_list[0].lat >10 && gcs_waypoints_list[0].lng > 0){
      update_home(true, gcs_waypoints_list[0].lng, gcs_waypoints_list[0].lat);
    }
  }
  /*map_set_viewpoints();*/
  if(gcs_waypoints_list.length > 0){
    setTimeout('map_set_viewpoints()',500);
  }
  else{
    setTimeout('map_center_and_zoom(map_center, 16)',500);
  }
  // palyback init
  start_index = pbinfo.start_index;
  end_index = pbinfo.end_index;
  start_time = pbinfo.start_time;
  end_time = pbinfo.end_time;
  total_time = (end_time - start_time).toFixed(0);
  var total_min = zeroPad(Math.abs((total_time/1000/60).toFixed(0)), 2);
  var total_sec = zeroPad(Math.abs((total_time/1000%60).toFixed(0)), 2);
  document.getElementById("replay-playtime").innerHTML = total_min + ':'+ total_sec;
  pb_get_line(start_index);
  pb_cur_index = start_index;
  /*pb_move_to(start_index);*/
  pb_paused = true;
  // reset pause button
  onPause();
}

function zeroPad(num, places) {
  var zero = places - num.toString().length + 1;
  return Array(+(zero > 0 && zero)).join("0") + num;
}

function get_time_format(now){
  var filename = '';
  filename += (now.getYear()+1900);
  filename += '-' + zeroPad(parseInt(now.getMonth())+1, 2);
  filename += '-' + zeroPad(now.getDate(), 2);
  filename += '-' + zeroPad(now.getHours(), 2);
  filename += '-' + zeroPad(now.getMinutes() ,2);
  filename += '-' + zeroPad(now.getSeconds(), 2);
  var format_time = '';
  format_time += (now.getYear()+1900);
  format_time += '-' + zeroPad(parseInt(now.getMonth())+1, 2);
  format_time += '-' + zeroPad(now.getDate(), 2);
  format_time += ' ' + zeroPad(now.getHours(), 2);
  format_time += ':' + zeroPad(now.getMinutes() ,2);
  format_time += ':' + zeroPad(now.getSeconds(), 2);
  return {
    filename: filename,
    format_time: format_time
  }
}

function pb_get_time(index){
  if(index < 1 || index > end_index) return 0;
  var line = pb_get_line(index);
  var items = line.split(',')
  if(items.length < 2) return 0;
  var time = parseInt(items[0]);
  return time;
}

var cur_working_prog = 0;
function playback_updating_next(time_val){
  //console.log(cur_working_prog)
  if(time_val>0 && cur_working_prog>1){
    cur_working_prog = 1;
    return;
  }
  if(pb_cur_index < 2 || pb_cur_index > end_index - 1){
    console.log('pb_cur_index error');
    return;
  }
  if(pb_cur_index == end_index - 1){
    console.log("回放结束");
    onPause();
    return;
  }
  var line = pb_get_line(pb_cur_index);
  if(line === null){
    console.log('pb_get_line null');
    onpause();
    return;
  }
  var items = line.split(',')
  if(items.length < 2){
    console.log('items length error');
    return;
  }
  var time = parseInt(items[0]);
  var type = parseInt(items[1]);
  pb_update_line(pb_cur_index);
  pb_update_frontend(type);
  if(time_val>0) cur_working_prog -= 1;
  // calculate time delta to control playback
  var last_time = pb_get_time(pb_cur_index - 1);
  if(last_time == 0){
    pb_cur_index += 1;
    playback_updating_next(0);
  }
  var time_delta = time - last_time;
  if(time_delta > 1000 || time_delta < 0) time_delta = 0;
  if(time_delta > 0){
    setTimeout(function (){
      if(!pb_paused){
        pb_cur_index += 1;
        playback_updating_next(time_delta);
      }
    }, time_delta);
    cur_working_prog += 1;
  }
  else{
    pb_cur_index += 1;
    playback_updating_next(0);
  }
}

function pb_update_line(index){
  var line = pb_get_line(index);
  if(line === null){
    console.log('pb_get_line null');
    onpause();
    return;
  }
  var items = line.split(',')
  if(items.length < 2){
    console.log('items length error');
    return;
  }
  var time = parseInt(items[0]);
  var type = parseInt(items[1]);
  if(type == PB_MSG_TYPE_HEARTBEAT){
    pb_base_status.system_is_armed = items[2];
    pb_base_status.armed = items[3];
    pb_base_status.custom_mode = items[4];
    pb_base_status.base_mode = items[5];
    pb_base_status.frame_type = items[6];
    pb_base_status.autopilot_type = items[7];
    pb_base_status.system_status = items[8];
  }
  else if(type == PB_MSG_TYPE_ATTITUDE){
    pb_attitude.roll = items[2];
    pb_attitude.pitch = items[3];
    pb_attitude.yaw = items[4];
    pb_attitude.rollspeed = items[5];
    pb_attitude.pitchspeed = items[6];
    pb_attitude.yawspeed = items[7];
  }
  else if(type == PB_MSG_TYPE_GPS_RAW_INT){
    pb_gps_raw_int.fix_type = items[2];
    pb_gps_raw_int.lat = items[3];
    pb_gps_raw_int.lon = items[4];
    pb_gps_raw_int.alt = items[5];
    pb_gps_raw_int.eph = items[6];
    pb_gps_raw_int.epv = items[7];
    pb_gps_raw_int.vel = items[8];
    pb_gps_raw_int.cog = items[9];
    pb_gps_raw_int.satellites_visible = items[10];
  }
  else if(type == PB_MSG_TYPE_SYS_STATUS){
    pb_sys_status.cpu_load = items[2];
    pb_sys_status.sensors_present = items[3];
    pb_sys_status.sensors_enabled = items[4];
    pb_sys_status.sensors_health = items[5];
    pb_sys_status.battery_voltage = items[6];
    pb_sys_status.battery_current = items[7];
    pb_sys_status.battery_remaining = items[8];
  }
  else if(type == PB_MSG_TYPE_RC_CHANNELS){
    pb_rc_channels.chan1_raw = items[2];
    pb_rc_channels.chan2_raw = items[3];
    pb_rc_channels.chan3_raw = items[4];
    pb_rc_channels.chan4_raw = items[5];
    pb_rc_channels.chan5_raw = items[6];
    pb_rc_channels.chan6_raw = items[7];
    pb_rc_channels.chan7_raw = items[8];
    pb_rc_channels.chan8_raw = items[9];
  }
  else if(type == PB_MSG_TYPE_MISSION_CURRENT){
    pb_mission_current.seq = items[2];
  }
  else if(type == PB_MSG_TYPE_GLOBAL_POSITION){
    pb_global_position.lat = items[2];
    pb_global_position.lon = items[3];
    pb_global_position.alt = items[4];
    pb_global_position.relative_alt = items[5];
    pb_global_position.vx = items[6];
    pb_global_position.vy = items[7];
    pb_global_position.vz = items[8];
    pb_global_position.hdg = items[9];
  }
}

function pb_update_frontend(type){
  var cur_time = pb_get_cur_time();
  if(cur_time < 0) cur_time = 0;
  var cur_min = zeroPad(Math.abs(cur_time/1000/60).toFixed(0), 2);
  var cur_sec = zeroPad(Math.abs(cur_time/1000%60).toFixed(0), 2);
  document.getElementById("replay-curtime").innerHTML = cur_min + ':' + cur_sec;
  var cur_prog = (pb_cur_index - start_index)/(end_index - start_index)*100;
  if(cur_prog < 0) cur_prog = 0;
  progress_value('replay-progress', cur_prog.toString() + '%');
  if(type == PB_MSG_TYPE_HEARTBEAT){
    //pb_base_status
    var base_status = pb_base_status;
    if(base_status.custom_mode == 3){
      document.getElementById("autocontrol-button").style.backgroundImage = 'url(./images/icon/auto.png)'
    }
    else if(base_status.custom_mode == 6){
      document.getElementById("autocontrol-button").style.backgroundImage = 'url(./images/icon/rtl.png)'
    }
    else if(base_status.custom_mode == 9){
      document.getElementById("autocontrol-button").style.backgroundImage = 'url(./images/icon/land.png)'
    }
    else{
      document.getElementById("autocontrol-button").style.backgroundImage = 'url(./images/icon/manu.png)'
    }
    if(base_status.system_is_armed){
      /*document.getElementById("lock-button").style.backgroundImage = 'url(./icon/unlock-blue.png)'*/
    }
    else{
      /*document.getElementById("lock-button").style.backgroundImage = 'url(./icon/lock-blue.png)'*/
    }
  }
  else if(type == PB_MSG_TYPE_ATTITUDE){
    //pb_attitude
    /*document.getElementsByClassName('dial-circle')[0].setAttribute("style","transform: translateX(26px) scale(1.5) rotate("+ (- pb_attitude.yaw/Math.PI*180) +"deg)");*/
    /*fillSky(pb_attitude.roll, pb_attitude.pitch);*/
    // radar
    /*document.getElementById('plane-rotate').setAttribute("style","transform:rotate("+ pb_attitude.yaw/Math.PI*180 +"deg)");*/
    /*sector(pb_attitude.yaw - Math.PI/2);*/
  }
  else if(type == PB_MSG_TYPE_GPS_RAW_INT){
    //pb_gps_raw_int
    var base_status = pb_base_status;
    var hor_speed = ((Math.sqrt(pb_global_position.vx*pb_global_position.vx + pb_global_position.vy*pb_global_position.vy))/1E2).toFixed(1);
    var ver_speed = (pb_global_position.vz/1E2).toFixed(1);
    var bd09 = wgs84tobd09(pb_gps_raw_int.lon/1E7, pb_gps_raw_int.lat/1E7);
    cur_position = new BMap.Point(bd09[0], bd09[1]);
    if(waypoint_markers_list.length > 0 && home_valid){
      dis_from_home = map.getDistance(waypoint_markers_list[0].getPosition(), cur_position);
    }
    if(plane_marker == undefined || plane_marker == null){
      plane_marker = new BMap.Marker(cur_position);
      map.addOverlay(plane_marker);
      plane_marker.setIcon(plane_icon);
      plane_marker.setTop(true);
      plane_marker.setZIndex(1);
    }
    plane_marker.setPosition(cur_position);
    plane_marker.setRotation(pb_attitude.yaw*180.0/Math.PI);
    var height = (pb_gps_raw_int.relative_alt/1000).toFixed(2);
    var lat = (pb_gps_raw_int.lat/1E7).toFixed(6);
    var lon = (pb_gps_raw_int.lon/1E7).toFixed(6);
    cur_lng = lat;
    cur_lon = lon;
    gps_fix_type = pb_gps_raw_int.fix_type;
    if(overall_dis > 72000){
      overall_dis = 0;
    }
    var hdop = pb_gps_raw_int.eph;
    if(hdop == 65535){
      hdop = 0;
    }
    var vdop = pb_gps_raw_int.epv;
    if(vdop == 65535){
      vdop = 0;
    }
    if(document.readyState == 'complete'){
      document.getElementById('panel-speedX').innerHTML = '' + hor_speed;
      /*document.getElementById('panel-speedZ-arrow').style.display = 'block';*/
      document.getElementById('panel-speedZ').innerHTML = '' + Math.abs(ver_speed).toFixed(1);
      /*document.getElementById('panel-lat').innerHTML = '' + lat;*/
      /*document.getElementById('panel-lng').innerHTML = '' + lon;*/
      document.getElementById('panel-flightheight').innerHTML = '' + height;
      // drawSpeedPanel(ctx_Z, Math.abs(ver_speed));
      // drawSpeedPanel(ctx_X, hor_speed);
      document.getElementById('satellite-number').innerHTML = '' + pb_gps_raw_int.satellites_visible;
      document.getElementById('panel-flightspan').innerHTML = '' + overall_dis.toFixed(1);
      document.getElementById('panel-flightdistance').innerHTML = '' + dis_from_home.toFixed(1);
      /*document.getElementById('panel-hdop').innerHTML = '' + hdop;*/
      /*document.getElementById('panel-vdop').innerHTML = '' + vdop;*/
    }
    update_track_line(cur_position);
    if(last_pos == 0){
      last_pos = cur_position;
    }
    else{
      var distance = map.getDistance(last_pos, cur_position);
      if(distance >= 1){
        last_pos = cur_position;
        overall_dis += distance;
      }
    }
  }
  else if(type == PB_MSG_TYPE_SYS_STATUS){
    //pb_sys_status
    /*battery_voltage = (pb_sys_status.battery_voltage/1E3).toFixed(2);*/
    /*document.getElementById('panel-battery').innerHTML = ''+battery_voltage;*/
    /*var battery_volume = (battery_voltage - BATT_MIN)/(BATT_MAX - BATT_MIN);*/
    // if(battery_volume > 0.75){
    //   document.getElementById("battery-volume").src = './icon/battery-green.png';
    // }
    // else if(battery_volume > 0.50){
    //   document.getElementById("battery-volume").src = './icon/battery-blue.png';
    // }
    // else if(battery_volume > 0.25){
    //   document.getElementById("battery-volume").src = './icon/battery-orange.png';
    // }
    // else if(battery_volume > 0){
    //   document.getElementById("battery-volume").src = './icon/battery-red.png';
    // }
    // else{
    //   document.getElementById("battery-volume").src = './icon/battery.png';
    // }
    // document.getElementById('panel-lefttime').innerHTML = '' + update_left_time().toFixed(1);
    // if(battery_volume < 0){
    //   battery_volume = 0;
    // }
    // document.getElementById('panel-battery-percent').innerHTML = '' + (battery_volume*100).toFixed(0);
  }
  else if(type == PB_MSG_TYPE_RC_CHANNELS){
    //pb_rc_channels
    /*document.getElementById('chan1').setAttribute('value', (pb_rc_channels.chan1_raw-1000).toString());*/
    /*document.getElementById('chan2').setAttribute('value', (pb_rc_channels.chan2_raw-1000).toString());*/
    /*document.getElementById('chan3').setAttribute('value', (pb_rc_channels.chan3_raw-1000).toString());*/
    /*document.getElementById('chan4').setAttribute('value', (pb_rc_channels.chan4_raw-1000).toString());*/
    /*document.getElementById('chan6').setAttribute('value', (pb_rc_channels.chan6_raw-1000).toString());*/
    /*document.getElementById('chan7').setAttribute('value', (pb_rc_channels.chan7_raw-1000).toString());*/
    /*document.getElementById('chan8').setAttribute('value', (pb_rc_channels.chan8_raw-1000).toString());*/
  }
  else if(type == PB_MSG_TYPE_MISSION_CURRENT){
    //pb_mission_current
    if(pb_mission_current.seq >= 0 && pb_mission_current.seq < gcs_waypoints_list.length){
      var cur_index = pb_mission_current.seq;
      if(cur_index == undefined || cur_index == null) return;
      if(cur_index >=0 && cur_index < gcs_waypoints_list.length){
        /*document.getElementById('curNo').innerHTML = '' + cur_index;*/
        /*document.getElementById('curH').innerHTML = '' + gcs_waypoints_list[cur_index].alt.toFixed(0);*/
        /*document.getElementById('curV').innerHTML = '' + gcs_waypoints_list[cur_index].speed.toFixed(1);*/
        /*document.getElementById('curT').innerHTML = '' + gcs_waypoints_list[cur_index].hold_time.toFixed(0);*/
      }
    }
  }
}

function pb_move_to(index){
  if(index < 2 || index > end_index - 1) return;
  if(index < 12) index = 12;
  clear_track_line();
  track_line_points=[];
  console.log('move to '+index);
  var track_points_lines = track_points_data.split('\n');
  for(var i=2; i<track_points_lines.length;i++){
    var line = track_points_lines[i];
    var items = line.split(',')
    var point_index = parseInt(items[0])
    if(point_index > index){
      break;
    }
    var bd09 = wgs84tobd09(items[1]/1E7, items[2]/1E7);
    cur_position = new BMap.Point(bd09[0], bd09[1]);
    track_line_points.push(cur_position);
  }
  track_line.setPath(track_line_points);
  track_line.show();
  pb_cur_index = index;
  for(var i=index-10; i<index ;i++){
    var line = pb_get_line(i);
    if(line === null){
      console.log('pb_get_line null');
      onpause();
      return;
    }
    var items = line.split(',')
    if(items.length < 2){
      console.log('items length error');
      return;
    }
    var time = parseInt(items[0]);
    var type = parseInt(items[1]);
    pb_update_line(i);
    pb_update_frontend(type);
  }
}

function pb_play(working_pro){
  pb_paused = false;
  document.getElementById("replay-play-li").style.display = "none";
  document.getElementById("replay-pause-li").style.display = "block";
  //cur_working_prog = 0;
  cur_working_prog = working_pro;
  playback_updating_next(0);
}

function pb_pause(){
  pb_paused = true;
  document.getElementById("replay-pause-li").style.display = "none";
  document.getElementById("replay-play-li").style.display = "block";
}

var win_left = 0;
var win_right = 0;
var pb_lines = [];
var index_move_to = 0;
var on_next_loading = false;
function pb_get_line(index){
  if(index < win_left || index >= win_right){
    var left = index - 500;
    var right = index + 1000;
    if(left < start_index){
      left = 1;
    }
    if(right > end_index){
      right = end_index -5;
    }
    index_move_to = index;
    request_pbseg(cur_pb_name, left, right);
    // pause here?
    return null;
  }
  if(index - win_left >= 1000){
    pb_lines.splice(0, 500);
    win_left = win_left + 500;
    console.log('win_left changed to '+ win_left);
    console.log('pb_lines length '+ pb_lines.length);
  }
  if(win_right - index < 500){
    if(!on_next_loading){
      var right = win_right + 500;
      if(right > end_index){
        right = end_index -5;
      }
      on_next_loading = true;
      request_pbseg(cur_pb_name, win_right, right);
    }
  }
  return pb_lines[index - win_left];
}

function pb_get_cur_time(){
  if(end_index < start_index) return 0;
  return total_time*(pb_cur_index - start_index)/(end_index - start_index);
}

function onPlay(){
  console.log('onplay')
  pb_play(0);
}

function onPause(){
  console.log('onpause')
  pb_pause();
}

function onStepForward(){
  if(pb_cur_index + 100 > end_index){
    pb_pause();
    pb_move_to(end_index);
  }
  if(pb_paused){
    pb_move_to(pb_cur_index + 100);
  }
  else{
    pb_pause();
    pb_move_to(pb_cur_index + 100);
    pb_play(cur_working_prog);
  }
}

function onStepBackword(){
  var target_index = pb_cur_index - 100;
  target_index = target_index<0 ? start_index : target_index;
  if(pb_paused){
    pb_move_to(pb_cur_index - 100);
  }
  else{
    pb_pause();
    pb_move_to(pb_cur_index - 100);
    pb_play(cur_working_prog);
  }
}

function progress_value(id, value){ //进度条赋值
  document.getElementById(id).style.width = value;
}

// 进度条点击 960 8
document.getElementById('replay-progress-div').addEventListener('click', function(e){
  var value = e.offsetX / 9.6;
  document.getElementById('replay-progress').style.width = "" + Math.ceil(value) + "%";
  console.log(value);
  var pb_dst_index = parseInt((end_index - start_index)*(value/100));
  if(pb_dst_index >= win_left && pb_dst_index < win_right){
    pb_move_to(pb_dst_index);
  }
  else{
    pb_get_line(pb_dst_index);
  }
});

//页码点击
function initFlyPages(){ //初始化列表，页码为1
  //获取总记录数 recordNum
  var fly_pages = document.getElementById("fly-pages");
  var n = Math.ceil(recordNum / records_per_page);
  allpagenum = n;
  clearFlyPages(fly_pages);
  document.getElementById('fly-totalpages').innerHTML = n;
  addLiToFlyPages(fly_pages, 1, '«');
  addLiToFlyPages(fly_pages, 1, '←');
  for(var i=1; i<=5; i++){
    if(i<=n) addLiToFlyPages(fly_pages, 1, i);
  }
  addLiToFlyPages(fly_pages, 1, '→');
  addLiToFlyPages(fly_pages, 1, '»');
}
function addLiToFlyPages(fly_pages, curpagechar, pagechar){ //页码行添加元素
  var fly_pages_li = document.createElement('LI');
  var fly_pages_a = document.createElement('A');
  fly_pages_a.innerHTML = pagechar;
  fly_pages_a.onclick = function(){
    clickFlyPages(curpagechar, pagechar);
  }
  if(curpagechar == pagechar) {
    fly_pages_li.className = 'active';
    curpagenum = pagechar;
    //获取并生成对应页码的记录列表
    /*console.log("当前页："+ pagechar);*/
    clean_flight_markers();
    flight_marker_points = [];
    load_cur_page();
  }
  else fly_pages_li.className = '';;
  fly_pages_li.appendChild(fly_pages_a);
  fly_pages.appendChild(fly_pages_li);
  //初始化第一页的记录
}
function clickFlyPages(curpagechar, pagechar){ //点击重置列表和页码
  //请求总记录数 recordNum
  clearFlyRecordsFromList();

  var fly_pages = document.getElementById("fly-pages");
  var n = Math.ceil(recordNum / records_per_page);
  document.getElementById('fly-totalpages').innerHTML = n;
  clearFlyPages(fly_pages);
  curpagechar = parseInt(curpagechar);
  if(pagechar=='«') pagechar = 1;
  if(pagechar=='←') pagechar = Math.max(curpagechar - 1, 1);
  if(pagechar=='→') pagechar = Math.min(curpagechar + 1, n);
  if(pagechar=='»') pagechar = n;
  pagechar = parseInt(pagechar);

  addLiToFlyPages(fly_pages, pagechar, '«');
  addLiToFlyPages(fly_pages, pagechar, '←');
  if(n>=5 && n-2 <= pagechar) {
    /*console.log(1);*/
    for(var i=n-4; i<=n; i++){
      addLiToFlyPages(fly_pages, pagechar, i);
    }
  }
  else if(pagechar <= 3) {
    /*console.log(2);*/
    /*console.log(n);*/
    for(var i=1; i<=5; i++){
      if(i<=n) addLiToFlyPages(fly_pages, pagechar, i);
    }
  }
  else {
    for(var i=pagechar-2; i<=pagechar+2; i++){
      addLiToFlyPages(fly_pages, pagechar, i);
    }
  }
  addLiToFlyPages(fly_pages, pagechar, '→');
  addLiToFlyPages(fly_pages, pagechar, '»');

  //获取当前点击页对应的记录

}
function clearFlyPages(fly_pages){  //清除当前页码栏
  var rm = fly_pages.getElementsByTagName('LI');
  for(var i=0; i<rm.length;){
    fly_pages.removeChild(rm[i]);
  }
}

function modify_position(index, pos_info){
  var media = document.getElementById('fly-records-div').getElementsByClassName('media')[index];
  var media_position = media.getElementsByClassName('media-position')[0];
  media_position.innerHTML = pos_info;
}

function load_cur_page(){
  for(var i=(curpagenum-1)*records_per_page;i<recordNum && i<curpagenum*records_per_page;i++){
    var flight = flight_his_list[i];
    var date_format = get_time_format(new Date(flight.start_time));
    var bd09 = wgs84tobd09(flight.loc_lng, flight.loc_lat);
    var pt = new BMap.Point(bd09[0], bd09[1]);
    var min = (flight.time/60).toFixed(0);
    var sec = (flight.time%60).toFixed(0);
    var time_str = min + '分' + sec + '秒';
    addFlyRecordToList(i, date_format.format_time, "11", time_str);
    draw_new_flight(pt, i+1);
    flight_marker_points.push(pt);
  }
  all_map_set_viewpoints();
  var j=0;
  for(var i=(curpagenum-1)*records_per_page;i<recordNum && i<curpagenum*records_per_page;i++){
    var bd09 = wgs84tobd09(flight.loc_lng, flight.loc_lat);
    var pt = new BMap.Point(bd09[0], bd09[1]);
    /*addFlyRecordToList(i, date_format.format_time, "11", time_str);*/
    geoc.getLocation(pt, function(rs){
      var addComp = rs.addressComponents;
      /*modify_position(j++, addComp.city + " " + addComp.district + " " + addComp.street);*/
      var address = addComp.city + " " + addComp.district + " " + addComp.street;
      /*console.log(address);*/
      modify_position(j++, address);
    });
  }
}

//生成记录到列表div 参数(记录编号 时间 地点 时长)
function addFlyRecordToList(index, time, pos, range){
  var fly_records_div = document.getElementById('fly-records-div');

  var media = document.createElement('DIV');
  media.className = "media";

  var media_a = document.createElement('A');
  media_a.className = "pull-left pos-rel";
  media_a.dataset.toggle = "modal";
  media_a.href="#myReplay";
  media_a.onclick=function(){
    curRecordIndex = index; //当链接被点击时修改当前记录
    console.log(uav_number+'-'+flight_his_list[index].playback_file_name.substring(8, 27));
    cur_pb_name = uav_number+'-'+flight_his_list[index].playback_file_name.substring(8, 27);
    request_pbinfo(cur_pb_name);
  };
  var media_a_img = document.createElement('IMG');
  media_a_img.className = "pos-abs";
  media_a_img.src = "images/blog/blog-thumb-1.jpg";
  var media_a_i = document.createElement('I');
  media_a_i.className = "glyphicon glyphicon-play-circle pos-abs float-play-button";
  media_a.appendChild(media_a_img);
  media_a.appendChild(media_a_i);
  media.appendChild(media_a);

  var media_div = document.createElement('DIV');
  media_div.className = "media-body fly-record-info";
  var media_div_h = document.createElement('H5');
  media_div_h.className = "media-heading";
  var media_div_a = document.createElement('A');
  media_div_a.innerHTML = time; //记录的时间
  media_div_h.appendChild(media_div_a);
  media_div.appendChild(media_div_h);
  var media_div_p1 = document.createElement('P');
  var media_div_p1_span = document.createElement('SPAN');
  media_div_p1_span.innerHTML = "地点："+ pos; //记录的地点
  media_div_p1_span.className = "media-position";
  media_div_p1.appendChild(media_div_p1_span);
  media_div.appendChild(media_div_p1);
  var media_div_p2 = document.createElement('P');
  var media_div_p2_span = document.createElement('SPAN');
  media_div_p2_span.innerHTML = "时长："+ range; //记录的时长
  media_div_p2.appendChild(media_div_p2_span);
  media_div.appendChild(media_div_p2);
  media.appendChild(media_div);  

  fly_records_div.appendChild(media);
}
function clearFlyRecordsFromList(){ //清除列表记录
  var rm = document.getElementById('fly-records-div').getElementsByClassName('media');
  for(var i=0; i<rm.length;){
    document.getElementById('fly-records-div').removeChild(rm[i]);
  }
}
